/*
 *  Copyright (c) Skrumtious
 */
package com.skrumtious.action;

import com.skrumtious.action.bean.ErrorBean;
import com.skrumtious.action.bean.SkrumItemBean;
import com.skrumtious.backend.DoAddSkrumItemRequest;
import com.skrumtious.backend.DoAddSkrumItemResponse;
import com.skrumtious.backend.SkrumService;
import com.skrumtious.backend.SkrumServiceFactory;
import com.skrumtious.backend.persistence.SkrumItem;

/**
 * @author Tony
 *
 */
public class AddSkrumItemWebAction implements WebAction {

	/* (non-Javadoc)
	 * @see com.skrumtious.action.WebAction#doAction(com.skrumtious.action.WebRequest)
	 */
	@Override
	public WebResponse doAction(WebRequest request) throws Exception {
		WebResponse response = null;
		
		SkrumService skrumService = SkrumServiceFactory.getSkrumService();
		
		String text = request.getParamAsString("text");
		int tabId = request.getParamAsInt("tabId");
		
		SkrumItem skrumItem = new SkrumItem(true, 1, text);
		
		DoAddSkrumItemRequest skrumRequest = new DoAddSkrumItemRequest(request.getUserId(), tabId, skrumItem);
		DoAddSkrumItemResponse skrumResponse = skrumService.addSkrumItem(skrumRequest);
				
		if ( ! skrumResponse.isSuccess() ) {
			String errorMsg = skrumResponse.getHumanReadableError();
			ErrorBean errorBean = new ErrorBean(errorMsg);
			request.setBean(ErrorBean.BEAN_NAME, errorBean);
			
			response = new WebResponse(true, false, "error.jsp");
		}
		else {				
			SkrumItemBean itemBean = new SkrumItemBean(tabId, skrumItem);
			request.setBean(SkrumItemBean.BEAN_NAME, itemBean);
			
			response = new WebResponse(true, false, "skrumitem.jsp");
		}
						
		return response;
	}

}
